package com.galeno.topn;

import com.alibaba.fastjson.JSON;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Author:   galeno
 * Date:     21/07/28
 * Description:
 * <p>
 * 输出每部电影评分最高的前3条记录
 * 1.Key排序
 * 2.Key序列化
 * 3.分区重写
 */
public class TopN {

    static class TopNMapper extends Mapper<LongWritable, Text, MovieBean, NullWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            try {
                String line = value.toString();
                MovieBean mb = JSON.parseObject(line, MovieBean.class);
                //经过环形缓冲区   数据分区
                context.write(mb, NullWritable.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class TopNReducer extends Reducer<MovieBean, NullWritable, MovieBean, NullWritable> {

        @Override
        protected void reduce(MovieBean key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
            int count = 0;
        try {
            for (NullWritable value : values) {
                context.write(key, NullWritable.get());
                count++;
                if (count == 3) {
                    return;
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }



        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf=new Configuration();
        conf.set("fs.defaultFS","file:/");
        Job job = Job.getInstance(conf,"TopN");

        job.setMapperClass(TopNMapper.class);
        job.setReducerClass(TopNReducer.class);



        job.setOutputKeyClass(MovieBean.class);
        job.setOutputValueClass(NullWritable.class);



        //
        job.setPartitionerClass(MyPartitioner.class);


        //
        job.setGroupingComparatorClass(MyGroupCompartor.class);


        FileInputFormat.setInputPaths(job,new Path("D:\\mrdata\\movie\\input"));
        FileOutputFormat.setOutputPath(job,new Path("D:\\mrdata\\movie\\out"));

        job.waitForCompletion(true);



    }

}
